package httpCtrler

import (
	"fmt"
	jwt "github.com/appleboy/gin-jwt"
	"github.com/gin-gonic/gin"
	"github.com/go-xorm/xorm"
	st "kjjcgroup_server/model"
	sv "kjjcgroup_server/service"
	"kjjcgroup_server/units"
	"net/http"
	"strconv"
	"time"
)

func UserRouter(router *gin.Engine, routerAuth *gin.RouterGroup) {
	routerAuth.GET("/userOne", userQuery)
	LogMap["/user"] = "查询单个用户"
	routerAuth.GET("/userMyInfo", loginUserQuery)
	LogMap["/userMyInfo"] = "查询当前登陆用户信息"
	routerAuth.GET("/operatorUser", operatorUser)
	LogMap["/operatorUser"] = "代理商查询的用户"
	routerAuth.GET("/userSearch", userSearch)
	LogMap["/userSearch"] = "用户搜索"
	routerAuth.GET("/userList", userList)
	LogMap["/userList"] = "分页查询用户"

	router.POST("/userReg", queryUserReg)
	LogMap["/userReg"] = "用户注册"
	router.POST("/resetPassword", resetPassword)
	LogMap["/resetPassword"] = "重置密码"
	router.GET("/checkAccount", sysCheckAccount)
	LogMap["/checkAccount"] = "检查账号是否存在"
	routerAuth.POST("/addUser", addUser)
	LogMap["/addUser"] = "添加用户"
	routerAuth.POST("/editUser", editUser)
	LogMap["/editUser"] = "编辑用户"
	routerAuth.POST("/delUser", delUser)
	LogMap["/delUser"] = "删除用户"
}

func userQuery(c *gin.Context) { // 想取哪个ID就输入ID值
	Id := c.Query("id")
	UserAccount := c.Query("UserAccount")
	WxUnionid := c.Query("WxUnionid")

	mysql, err := sv.GetEngine()
	if err != nil {
		c.JSON(http.StatusConflict, &MsgReturn{Msg: http.StatusText(http.StatusConflict), Data: nil})
		return
	}
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {
			return
		}
	}(mysql)
	mysql.ShowSQL(isShowSQL())
	var collArr []*st.ModSysUser
	if Id != "" {
		err = mysql.Where("user_id=?", Id).Find(&collArr)
	} else if UserAccount != "" {
		err = mysql.Where("user_account=?", UserAccount).Find(&collArr)
	} else if WxUnionid != "" {
		err = mysql.Where("wx_unionid=?", WxUnionid).Find(&collArr)
	}
	if err != nil {
		fmt.Println(err)
		c.JSON(http.StatusConflict, &MsgReturn{Msg: http.StatusText(http.StatusConflict), Data: nil})
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: collArr})
}

func loginUserQuery(c *gin.Context) {
	// Auth := c.Query("auth")
	mysql, err := sv.GetEngine()
	CheckMysqlError(c, err) // 409
	defer DeferMysql(mysql)
	mysql.ShowSQL(isShowSQL())
	var collArr []*st.ModSysUser
	UserId := CurrentUserId(c)
	// UserAccount := CurrentAccount(c)
	err = mysql.Where("user_id=?", UserId).Find(&collArr)
	c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: collArr})

}

func operatorUser(c *gin.Context) {
	Keyword := c.Query("Keyword")

	mysql, err := sv.GetEngine()
	CheckMysqlError(c, err) // 409
	defer DeferMysql(mysql)
	mysql.ShowSQL(isShowSQL())
	var collArr []*st.ModSysUser
	var countNum []*st.SysUser
	UserId := CurrentUserId(c)
	pageIdx, pageCnt := Page(c)
	if pageIdx == -1 {
		pageIdx = 0
	}
	if pageCnt == -1 {
		pageCnt = 10
	}
	var count int64
	if Keyword != "" {
		err = mysql.Where("user_account LIKE ?", "%"+Keyword+"%").Or("user_name LIKE ? ", "%"+Keyword+"%").Or("user_phone LIKE ? ", "%"+Keyword+"%").And("adder_id = ?", UserId).Limit(pageCnt, pageIdx*pageCnt).Find(&collArr)
		count, _ = mysql.Where("user_account LIKE ?", "%"+Keyword+"%").Or("user_name LIKE ? ", "%"+Keyword+"%").Or("user_phone LIKE ? ", "%"+Keyword+"%").And("adder_id = ?", UserId).FindAndCount(&countNum)
	} else {
		err = mysql.Where("adder_id = ?", UserId).Limit(pageCnt, pageIdx*pageCnt).Find(&collArr)
		count, _ = mysql.Where("adder_id = ?", UserId).FindAndCount(&countNum)
	}
	rtnDt := rtnData(count, pageCnt, pageIdx, collArr)
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: rtnDt})
}

func userSearch(c *gin.Context) {
	// 判断权限搜索,代理商只能搜索到他的用户
	// 根据是用户还是运营商搜索
	PermissionId := c.Query("PermissionId")
	Keyword := c.Query("Keyword")

	pageIdx, pageCnt := Page(c)
	if pageIdx == -1 {
		pageIdx = 0
	}
	if pageCnt == -1 {
		pageCnt = 10
	}
	mysql, err := sv.GetEngine()
	units.CheckError(err)
	defer DeferMysql(mysql)
	mysql.ShowSQL(isShowSQL())
	var collArr []*st.ModSysUser
	var countNum []*st.SysUser
	var count int64
	clm := jwt.ExtractClaims(c)
	perm := clm[SessPermissionId]
	adderId := clm[SessUserId]
	if perm == "9" {
		if PermissionId != "" {
			err = mysql.Where("user_account LIKE ?", "%"+Keyword+"%").Or("user_name LIKE ? ", "%"+Keyword+"%").Or("user_phone LIKE ? ", "%"+Keyword+"%").And("permission_id=?", PermissionId).Limit(pageCnt, pageIdx*pageCnt).OrderBy("user_id desc").Find(&collArr)
			count, _ = mysql.Where("user_account LIKE ?", "%"+Keyword+"%").Or("user_name LIKE ? ", "%"+Keyword+"%").Or("user_phone LIKE ? ", "%"+Keyword+"%").And("permission_id=?", PermissionId).FindAndCount(&countNum)

		} else {
			err = mysql.Where("user_account LIKE ?", "%"+Keyword+"%").Or("user_name LIKE ? ", "%"+Keyword+"%").Or("user_phone LIKE ? ", "%"+Keyword+"%").Limit(pageCnt, pageIdx*pageCnt).OrderBy("create_time desc").Find(&collArr)
			count, _ = mysql.Where("user_account LIKE ?", "%"+Keyword+"%").Or("user_name LIKE ? ", "%"+Keyword+"%").Or("user_phone LIKE ? ", "%"+Keyword+"%").FindAndCount(&countNum)
		}
	} else { // 运营商搜索
		//	fmt.Printf("\033[8;31;40m%s\033[0m\n", adderId)
		err = mysql.Where("user_account LIKE ?", "%"+Keyword+"%").Or("user_name LIKE ? ", "%"+Keyword+"%").Or("user_phone LIKE ? ", "%"+Keyword+"%").And("adder_id = ?", adderId).Limit(pageCnt, pageIdx*pageCnt).OrderBy("user_id desc").Find(&collArr)
		count, _ = mysql.Where("user_account LIKE ?", "%"+Keyword+"%").Or("user_name LIKE ? ", "%"+Keyword+"%").Or("user_phone LIKE ? ", "%"+Keyword+"%").And("adder_id = ?", adderId).FindAndCount(&countNum)
	}
	rtnDt := rtnData(count, pageCnt, pageIdx, collArr)
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: rtnDt})
}

func userList(c *gin.Context) { // 想取哪个ID就输入ID值
	PermissionId := c.Query("PermissionId")
	Criteria := c.Query("criteria")

	pageIdx, pageCnt := Page(c)
	if pageIdx == -1 {
		pageIdx = 0
	}
	if pageCnt == -1 {
		pageCnt = 10
	}
	mysql, err := sv.GetEngine()
	units.CheckError(err)
	defer DeferMysql(mysql)
	mysql.ShowSQL(isShowSQL())

	var collArr1 []*st.ModSysUser
	var collArrL []*st.ModListSysUser
	var count int64
	if PermissionId != "" {
		err = mysql.Where("permission_id=? and (user_account LIKE ? or user_name LIKE ? or user_phone LIKE ?) ", PermissionId, "%"+Criteria+"%", "%"+Criteria+"%", "%"+Criteria+"%").Limit(pageCnt, pageIdx*pageCnt).OrderBy("create_time desc").Find(&collArrL)
		count, _ = mysql.Where("permission_id=? and (user_account LIKE ? or user_name LIKE ? or user_phone LIKE ?) ", PermissionId, "%"+Criteria+"%", "%"+Criteria+"%", "%"+Criteria+"%").FindAndCount(&collArr1)
	} else {
		err = mysql.Where("user_account LIKE ? or user_name LIKE ? or user_phone LIKE ? ", "%"+Criteria+"%", "%"+Criteria+"%", "%"+Criteria+"%").Limit(pageCnt, pageIdx*pageCnt).OrderBy("create_time desc").Find(&collArrL)
		count, _ = mysql.Where("user_account LIKE ? or user_name LIKE ? or user_phone LIKE ? ", "%"+Criteria+"%", "%"+Criteria+"%", "%"+Criteria+"%").FindAndCount(&collArr1)
	}
	if err != nil {
		fmt.Println(err)
		c.JSON(409, &MsgReturn{Msg: "failed", Data: nil})
		return
	}
	rtnDt := rtnData(count, pageCnt, pageIdx, collArrL)
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: rtnDt})
}

func queryUserReg(c *gin.Context) {
	resDt := &st.ModRegSysUser{}
	err := c.BindJSON(resDt)
	units.CheckError(err)
	/*检查用户是否存在*/
	if checkAccount(resDt.UserAccount) {
		c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusBadRequest), Data: "账号已存在!"})
		return
	}
	password := units.TokenEncrypt(resDt.UserPassword)
	mysql, err := sv.GetEngine()
	units.CheckError(err)
	defer func(mysql *xorm.Engine) {
		err := mysql.Close()
		if err != nil {

		}
	}(mysql)
	sess := mysql.NewSession()
	defer sess.Close()
	err = sess.Begin()
	units.CheckError(err)
	t := time.Now()
	t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, time.Local)
	_, err = sess.Cols("user_account", "user_password", "user_phone", "user_name", "user_sex", "user_email", "wechat", "wx_unionid", "open_id", "permission_id", "user_photo", "user_info", "project_id", "adder_id", "teach_name", "create_time").InsertOne(&st.ModAddSysUser{UserAccount: resDt.UserAccount, UserPassword: password, UserPhone: resDt.UserPhone, UserName: resDt.UserName, UserSex: resDt.UserSex, UserEmail: resDt.UserEmail, PermissionId: 3, UserInfo: resDt.UserInfo, ProjectId: resDt.ProjectId, AdderId: resDt.AdderId, TeachName: resDt.TeachName, CreateTime: t})
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
	if err != nil {
		c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusBadRequest), Data: "注册错误!"})
		return
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: "注册成功!"})
}

func resetPassword(c *gin.Context) {
	resDt := &struct {
		UserAccount  string `json:"UserAccount"`
		UserPassword string `json:"UserPassword"`
	}{}
	err := c.BindJSON(resDt)
	if !checkAccount(resDt.UserAccount) {
		c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: "用户不存在"})
		return
	}
	mysql, err := sv.GetEngine()
	units.CheckError(err)
	defer DeferMysql(mysql)
	mysql.ShowSQL(isShowSQL())
	sess := mysql.NewSession()
	defer sess.Close()
	password := units.TokenEncrypt(resDt.UserPassword)
	_, err = mysql.Where("user_account=?", resDt.UserAccount).Update(&st.ModLoginSysUser{UserPassword: password})
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: "账号: " + resDt.UserAccount + "重置密码成功!"})
}

func sysCheckAccount(c *gin.Context) {
	UserAccount := c.Query("UserAccount")
	isUser := checkAccount(UserAccount)
	c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: isUser})
}

func addUser(c *gin.Context) {
	resDt := &struct {
		Items []st.ModAddSysUser `json:"addUser" `
	}{}
	err := c.BindJSON(resDt)
	units.CheckError(err)
	// res2B, _ := json.Marshal(resDt)
	// fmt.Printf("\033[8;31;40m%s\033[0m\n", string(res2B))
	msg := ""
	for addItem := range resDt.Items {
		// 检查用户名是否重复,重复的不添加
		isAdd := checkAccount(resDt.Items[addItem].UserAccount)
		if !isAdd {
			addUserOne(resDt.Items[addItem])
			msg += resDt.Items[addItem].UserAccount + "添加成功! "
		} else {
			msg += resDt.Items[addItem].UserAccount + "已存在,未添加成功! "
		}
	}
	units.CheckError(err)
	c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: msg})
}

func editUser(c *gin.Context) {
	resDt := &st.ModAddSysUser{}
	err := c.BindJSON(resDt)
	units.CheckError(err)
	mysql, err := sv.GetEngine()
	units.CheckError(err)
	defer DeferMysql(mysql)
	mysql.ShowSQL(isShowSQL())
	sess := mysql.NewSession()
	defer sess.Close()
	err = sess.Begin()
	units.CheckError(err)
	//	fmt.Printf("\033[8;31;40m%s\033[0m\n", string(resDt.UserId))
	_, err = sess.Where("user_id=?", resDt.UserId).Update(&st.ModAddSysUser{UserPhone: resDt.UserPhone, UserName: resDt.UserName, UserSex: resDt.UserSex, UserNumber: resDt.UserNumber, UserEmail: resDt.UserEmail, PermissionId: resDt.PermissionId, UserPhoto: resDt.UserPhoto, UserInfo: resDt.UserInfo, ProjectId: resDt.ProjectId})
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: "OK", Data: "id:" + strconv.Itoa(resDt.UserId) + " 编辑成功!"})
}

func delUser(c *gin.Context) {
	resDt := &struct {
		Items []string `json:"user" `
	}{}
	err := c.BindJSON(resDt)
	units.CheckError(err)
	msg := ""
	for index := range resDt.Items {
		isAdd := checkAccount(resDt.Items[index])
		if isAdd {
			delUserOne(resDt.Items[index])
			msg += resDt.Items[index] + "删除成功! "
		} else {
			msg += resDt.Items[index] + "不存在,未删除成功! "
		}
	}
	c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: msg})
}

// 单个添加用户
func addUserOne(resDt st.ModAddSysUser) {
	mysql, err := sv.GetEngine()
	units.CheckError(err)
	defer DeferMysql(mysql)
	mysql.ShowSQL(isShowSQL())
	// 建立 mysql session
	sess := mysql.NewSession()
	defer sess.Close()

	t := time.Now()
	t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, time.Local)
	_, err = mysql.Cols("user_account", "user_password", "credits", "auth_soft", "auth_num", "soft_num", "auth_mac", "user_phone", "user_name", "user_sex", "user_number", "user_email", "wechat", "wx_unionid", "open_id", "org_id", "permission_id", "user_photo", "user_info", "status", "project_id", "adder_id", "teach_name", "create_time").InsertOne(&st.ModAddSysUser{UserAccount: resDt.UserAccount, UserPassword: units.TokenEncrypt(resDt.UserPassword), UserPhone: resDt.UserPhone, UserName: resDt.UserName, UserSex: resDt.UserSex, UserNumber: resDt.UserNumber, UserEmail: resDt.UserEmail, PermissionId: resDt.PermissionId, UserPhoto: resDt.UserPhoto, UserInfo: resDt.UserInfo, ProjectId: resDt.ProjectId, AdderId: resDt.AdderId, TeachName: resDt.TeachName, CreateTime: t})
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
	units.CheckError(err)
}

// 删除单个用户
func delUserOne(account string) {
	mysql, err := sv.GetEngine()
	units.CheckError(err)
	defer DeferMysql(mysql)
	mysql.ShowSQL(isShowSQL())
	sess := mysql.NewSession()
	defer sess.Close()
	_, err = mysql.Where("user_account=?", account).Delete(&st.ModSysUser{})
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
}

// 检查账号是否存在
func checkAccount(account string) bool {
	// fmt.Printf("\033[8;31;40m%s\033[0m\n", account)
	mysql, err := sv.GetEngine()
	units.CheckError(err)
	defer DeferMysql(mysql)
	mysql.ShowSQL(isShowSQL())
	res := &st.ModLoginSysUser{}
	has, _ := mysql.Where("user_account=?", account).Get(res)
	return has
}

type UserAuth struct {
	StartTime time.Time `json:"StartTime"`
	EndTime   time.Time `json:"EndTime"`
}
